package com.sen.gulimall.seckill.scheduled;

import com.sen.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author Kisen
 * @email lqs0911@qq.com
 * @date 2023/1/31 14:36
 * @detail 秒杀商品定时上架
 * 每天晚上3点，上架最近三天需要秒杀的商品
 * 当天00:00:00 - 23:59:59
 * 明天00:00:00 - 23:59:59
 * 后天00:00:00 - 23:59:59
 */
@Slf4j
@Service
public class SeckillScheduled {

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedissonClient redissonClient;

    private final String UPLOAD_LOCK = "seckill:uload:lock";

    //TODO 幂等性处理
    @Async
    @Scheduled(cron = "0 */3 * * * ?")
    public void uploadSeckillSkuLastest3Days() {
        //1、重复上架无需处理
        log.info("上架秒杀的商品信息...");
        //分布式锁
        RLock lock = redissonClient.getLock(UPLOAD_LOCK);
        try {
            lock.lock(10, TimeUnit.SECONDS);
            seckillService.uploadSeckillSkuLastest3Days();
        } finally {
            lock.unlock();
        }
    }


}
